package com.aiju.cash.ui.member;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.MemberApi;
import com.aiju.cash.core.api.MemberPointApi;
import com.aiju.cash.ui.member.adater.MemberInfoCardAdapter;
import com.aiju.cash.ui.member.entity.Member;
import com.aiju.cash.ui.member.entity.MemberCard;
import com.aiju.cash.util.MathUtil;
import com.aiju.utils.KeyBoardUtils;
import com.aiju.utils.T;
import com.aiju.widgit.dialog.EditPointDialog;
import com.aiju.widgit.layout.SettingItemTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2017-02-20 15:59
 * @version: V1.0
 * @Description: 会员详情(领取卡列表)
 */
public class MemberInfoCardsActivity extends BaseTitleActivity {

    private SettingItemTextView nameTextView, phoneTextView, pointTextView;

    private ListView cardListView;

    private boolean eidt;

    private Member member;
    private String memberId;
    private int type;

    private MemberInfoCardAdapter adapter;

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_info_cards);
        setCenterTitle("会员详情");
        //setRightTitle("编辑");

        type = getIntent().getIntExtra("type", -1);
        memberId = getIntent().getStringExtra("memberId");

        cardListView = (ListView) findViewById(R.id.lv_merber_card);
        nameTextView = (SettingItemTextView) findViewById(R.id.tv_member_name);
        phoneTextView = (SettingItemTextView) findViewById(R.id.tv_member_phone);
        pointTextView = (SettingItemTextView) findViewById(R.id.tv_member_point);


        requsetMember();

        pointTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MemberInfoCardsActivity.this, MemberPointsListActivity.class);
                intent.putExtra("memberPhone", member.getPhone());
                intent.putExtra("points", points);
                startActivity(intent);
            }
        });

        button = (Button) findViewById(R.id.btn_good_add_save);
        if (type == MemberSearchActivity.SELECT_MEMVER) {
            button.setText("下一步");
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (memberCard == null) {
                        if (findViewById(R.id.ly).isSelected()) {
                            showPointDialog();
                        } else {
                            Intent intent = new Intent();
                            intent.putExtra("memberPhone", member.getPhone());
                            setResult(100, intent);
                            showToast();
                            finish();
                        }
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("memberCard", memberCard);
                        setResult(100, intent);
                        showToast();
                        finish();
                    }
                }
            });
        } else {
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goMemberInfoActivity();
                }
            });
        }


        findViewById(R.id.tv_tip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goMemberCardList();
            }
        });
        cardListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (type == MemberSearchActivity.SELECT_MEMVER) {
                    memberCard = member.getCardList().get(position);
                    memberCard.setSelect(true);
                    for (MemberCard card : member.getCardList()) {
                        if (card != memberCard) {
                            card.setSelect(false);
                        }
                    }
                    findViewById(R.id.ly).setSelected(false);
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void showToast() {
        if (mUser.getMPoints() == null || mUser.getMPoints().getStatus().equals("0")) {
            return;
        }
        T.ToastShort(member.getPhone() + "累积积分");
    }

    private String points;
    private MemberCard memberCard;

    /**
     * 获取会员积分
     *
     * @param phone
     */
    private void requsetMemberPoint(String phone) {
        new MemberPointApi(null).getValidPoints(phone, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                if (TextUtils.isEmpty(data)||data.equals("null")) {
                    points = "0";
                }else {
                    points = data;
                }

                if (type == MemberSearchActivity.SELECT_MEMVER) {
                    pointTextView.setVisibility(View.GONE);
                    if (mUser.getMPoints() == null || mUser.getMPoints().getStatus().equals("0")) {
                        findViewById(R.id.ly).setVisibility(View.GONE);
                    } else {
                        findViewById(R.id.ly).setVisibility(View.VISIBLE);
                    }
                    findViewById(R.id.iv_member_select).setVisibility(View.VISIBLE);
                    ((TextView) findViewById(R.id.tv_member_points)).setText(points);
                    findViewById(R.id.ly).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            v.setSelected(true);
                            for (MemberCard card : member.getCardList()) {
                                card.setSelect(false);
                            }
                            adapter.notifyDataSetChanged();
                            //showPointDialog();
                        }
                    });
                } else {
                    findViewById(R.id.ly).setVisibility(View.GONE);
                    findViewById(R.id.iv_member_select).setVisibility(View.GONE);
                    if (mUser.getMPoints() == null || mUser.getMPoints().getStatus().equals("0")) {
                        pointTextView.setVisibility(View.GONE);
                    } else {
                        pointTextView.setVisibility(View.VISIBLE);
                    }
                    pointTextView.setRightText(points);
                }
            }
        });
    }

    private void showPointDialog() {
        new EditPointDialog(this)
                .initData(points)
                .setLayoutParams()
                .setOnEditClick(new EditPointDialog.OnEditClick() {
                    @Override
                    public void onCancel() {
                        memberCard = null;
                        KeyBoardUtils.closeKeybord(MemberInfoCardsActivity.this);
                    }

                    @Override
                    public void onSubmit(String msg) {
                        if (TextUtils.isEmpty(msg)) {
                            return;
                        }
                        memberCard = new MemberCard();
                        memberCard.setMemberPhone(member.getPhone());
                        memberCard.setType("3");
                        memberCard.setDiscount(msg);

                        Intent intent = new Intent();
                        intent.putExtra("memberCard", memberCard);
                        setResult(100, intent);
                        showToast();
                        finish();
                    }
                }).show();
    }

    private MemberCard bindCard;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (data != null && data.hasExtra("memberCard")) {
                bindCard = (MemberCard) data.getSerializableExtra("memberCard");
                if (bindCard != null) {
                    bindMemberCard(bindCard);
                } else {
                    T.ToastShort("选择会员卡失败");
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 跳转选择会员卡
     */
    private void goMemberCardList() {
        Intent intent = new Intent(this, MemberCardActivity.class);
        intent.putExtra("type", MemberCardActivity.SELECT);
        startActivityForResult(intent, 100);
    }

    // 	会员卡号
    private String code, mCardId;

    /**
     * 会员绑定会员卡
     */
    private void bindMemberCard(MemberCard card) {
        mDialogHelper.showLoadingProgressDialog();
        new MemberApi().bindCard(member.getId(), card.getId(), getCardCode(), mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mDialogHelper.dismissProgressDialog();
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson json = new DataJson(response);
                if (json.isSuccess()) {
                    T.ToastShort("绑定成功");
                    addBindCard();
                } else {
                    T.ToastShort(json.getMsg());
                }
            }
        });
    }

    private void addBindCard() {
        member.getCardList().add(bindCard);
        ((BaseAdapter) cardListView.getAdapter()).notifyDataSetChanged();
    }


    /**
     * 会员信息接口
     */
    private void requsetMember() {
        mDialogHelper.showLoadingProgressDialog();
        new MemberApi().memberGet(memberId, mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mDialogHelper.dismissProgressDialog();
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson json = new DataJson(response);
                if (json.isSuccess()) {
                    member = new Gson().fromJson(json.getData().toString(), new TypeToken<Member>() {
                    }.getType());
                    nameTextView.setRightText(member.getName());
                    phoneTextView.setRightText(member.getPhone());
                    adapter = new MemberInfoCardAdapter(MemberInfoCardsActivity.this, member.getCardList());
                    if (type == MemberSearchActivity.SELECT_MEMVER) {
                        adapter.setSelect(true);
                    }
                    cardListView.setAdapter(adapter);
                    if (member.getCardList().size() == 0) {
                        cardListView.setEmptyView(findViewById(R.id.tv_empty));
                    }
                    requsetMemberPoint(member.getPhone());
                } else {
                    T.ToastShort(json.getMsg());
                }
            }
        });
    }

    private String getCardCode() {
        return System.currentTimeMillis() + MathUtil.getFixLenthString(5);
    }

    /**
     * 跳转会员详情
     */
    private void goMemberInfoActivity() {
        Intent intent = new Intent(this, MemberInfoActivity.class);
        intent.putExtra("member", member);
        intent.putExtra("type", MemberInfoActivity.INFO);
        startActivity(intent);
    }
}
